import { MockMethod } from 'vite-plugin-mock'
import lodash from 'lodash'

type PriorityMockMethod = {
	priority: number
	mockMethod: MockMethod
}

class MockUtils {
	private mockList: PriorityMockMethod[] = []

	addMockList = (...items: MockMethod[]): void => {
		this.addPriorityMockList(0, ...items)
	}

	addPriorityMockList = (priority: number, ...items: MockMethod[]): void => {
		const self = this
		const newMockMethods = this.convertToPriorityMockMethod(priority, ...items)
		const oldMockMethods = self.mockList
		const allMockMethods = [...this.mockList, ...newMockMethods]
		const resultList = [] as PriorityMockMethod[]
		allMockMethods.forEach(mockMethod => {
			let resultMockMethod = mockMethod
			const oldMockMethod = self.findPriorityMockMethodByUrl(mockMethod.mockMethod.url, self.mockList)
			if (!lodash.isNil(oldMockMethod)) {
				resultMockMethod = mockMethod.priority >= oldMockMethod.priority ? mockMethod : oldMockMethod
			}
			resultList.push(resultMockMethod)
		})
		this.mockList = resultList
	}

	getMockMethodList = (): MockMethod[] => {
		return this.mockList.map(value => value.mockMethod)
	}

	convertToPriorityMockMethod = (priority: number, ...mockMethods: MockMethod[]): PriorityMockMethod[] => {
		return mockMethods.map(mockMethod => {
			return {
				priority: priority,
				mockMethod: mockMethod,
			} as PriorityMockMethod
		})
	}

	private findPriorityMockMethodByUrl = (
		url: string,
		priorityMockMethods: PriorityMockMethod[],
	): PriorityMockMethod | undefined => {
		return priorityMockMethods.find(value => value.mockMethod.url === url)
	}
}

export default new MockUtils()
